// 配置高德地图API密钥 (请替换为你的实际API Key)
const API_KEY = '2fe851c78c974c077565b4aa9e0002d5';
const WEATHER_URL = 'https://restapi.amap.com/v3/weather/weatherInfo';

// DOM 元素
const cityInput = document.getElementById('city-input');
const searchBtn = document.getElementById('search-btn');
const locationBtn = document.getElementById('location-btn');
const weatherInfo = document.getElementById('weather-info');
const errorMessage = document.getElementById('error-message');
const cityName = document.getElementById('city-name');
const temperature = document.getElementById('temperature');
const description = document.getElementById('description');
const feelsLike = document.getElementById('feels-like');
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('wind-speed');
const updateTime = document.getElementById('update-time');

// 搜索按钮事件监听
searchBtn.addEventListener('click', () => {
    const city = cityInput.value.trim();
    if (city) {
        getWeatherByCity(city);
    }
});

// 回车键搜索
cityInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        const city = cityInput.value.trim();
        if (city) {
            getWeatherByCity(city);
        }
    }
});

// 定位按钮事件监听
locationBtn.addEventListener('click', () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
                const { latitude, longitude } = position.coords;
                getWeatherByCoordinates(latitude, longitude);
            },
            error => {
                showError('无法获取您的位置信息，请手动输入城市名称');
            }
        );
    } else {
        showError('您的浏览器不支持地理定位功能');
    }
});

// 根据城市名称获取天气
async function getWeatherByCity(city) {
    try {
        console.log('正在查询城市:', city);
        // 首先通过高德地图地理编码API获取城市编码
        const geoResponse = await axios.get('https://restapi.amap.com/v3/geocode/geo', {
            params: {
                address: city,
                key: API_KEY
            }
        });
        
        console.log('地理编码API响应:', geoResponse.data);
        
        if (geoResponse.data.status === '1' && geoResponse.data.geocodes.length > 0) {
            const adcode = geoResponse.data.geocodes[0].adcode;
            console.log('获取到区域编码:', adcode);
            getWeatherByAdcode(adcode, city);
        } else {
            showError('无法找到该城市，请检查城市名称是否正确');
        }
    } catch (error) {
        console.error('查询城市信息出错:', error);
        showError('查询城市信息失败，请稍后重试');
    }
}

// 根据区域编码获取天气
async function getWeatherByAdcode(adcode, cityName) {
    try {
        console.log('正在查询天气，区域编码:', adcode);
        const response = await axios.get(WEATHER_URL, {
            params: {
                city: adcode,
                key: API_KEY,
                extensions: 'base'
            }
        });
        
        console.log('天气API响应:', response.data);
        
        if (response.data.status === '1' && response.data.lives.length > 0) {
            const weatherData = response.data.lives[0];
            // 构造适配原有界面的数据结构
            const adaptedData = {
                name: cityName || weatherData.city,
                sys: { country: 'CN' },
                main: {
                    temp: parseFloat(weatherData.temperature),
                    feels_like: parseFloat(weatherData.temperature), // 高德API没有体感温度，使用实际温度
                    humidity: parseFloat(weatherData.humidity)
                },
                wind: { speed: parseFloat(weatherData.windpower) || 0 },
                weather: [{ main: weatherData.weather, description: weatherData.weather }],
                dt: new Date().getTime() / 1000 // 使用当前时间
            };
            displayWeather(adaptedData);
        } else {
            showError('无法获取天气信息，请稍后重试');
        }
    } catch (error) {
        console.error('获取天气信息出错:', error);
        showError('获取天气信息失败，请稍后重试');
    }
}

// 根据经纬度获取天气
async function getWeatherByCoordinates(lat, lon) {
    try {
        console.log('正在获取位置信息，经纬度:', lat, lon);
        // 通过高德地图逆地理编码API获取区域编码
        const regeoResponse = await axios.get('https://restapi.amap.com/v3/geocode/regeo', {
            params: {
                location: `${lon},${lat}`,
                key: API_KEY
            }
        });
        
        console.log('逆地理编码API响应:', regeoResponse.data);
        
        if (regeoResponse.data.status === '1') {
            const adcode = regeoResponse.data.regeocode.addressComponent.adcode;
            const cityName = regeoResponse.data.regeocode.formatted_address;
            console.log('获取到区域编码和城市名称:', adcode, cityName);
            getWeatherByAdcode(adcode, cityName);
        } else {
            showError('无法获取位置信息，请手动输入城市名称');
        }
    } catch (error) {
        console.error('获取位置信息出错:', error);
        showError('获取位置信息失败，请稍后重试');
    }
}

// 显示天气信息
function displayWeather(data) {
    // 更新天气信息
    cityName.textContent = `${data.name}, ${data.sys.country}`;
    temperature.textContent = Math.round(data.main.temp);
    description.textContent = data.weather[0].description;
    feelsLike.textContent = Math.round(data.main.feels_like);
    humidity.textContent = data.main.humidity;
    windSpeed.textContent = data.wind.speed.toFixed(1);
    
    // 格式化更新时间
    const date = new Date(data.dt * 1000);
    updateTime.textContent = date.toLocaleString('zh-CN');
    
    // 设置背景样式
    setWeatherBackground(data.weather[0].main);
    
    // 显示天气信息，隐藏错误信息
    weatherInfo.classList.remove('hidden');
    errorMessage.classList.add('hidden');
}

// 设置天气背景样式
function setWeatherBackground(weatherMain) {
    // 移除所有天气类名
    document.body.className = '';
    
    // 根据天气主类型添加对应类名
    switch (weatherMain.toLowerCase()) {
        case '晴':
            document.body.classList.add('clear-sky');
            break;
        case '多云':
            document.body.classList.add('clouds');
            break;
        case '阴':
            document.body.classList.add('clouds');
            break;
        case '雨':
        case '小雨':
        case '中雨':
        case '大雨':
        case '暴雨':
            document.body.classList.add('rain');
            break;
        case '雷阵雨':
            document.body.classList.add('thunderstorm');
            break;
        case '雪':
        case '小雪':
        case '中雪':
        case '大雪':
            document.body.classList.add('snow');
            break;
        case '雾':
        case '霾':
            document.body.classList.add('mist');
            break;
        default:
            document.body.classList.add('clear-sky');
    }
}

// 显示错误信息
function showError(message) {
    errorMessage.querySelector('p').textContent = message;
    errorMessage.classList.remove('hidden');
    weatherInfo.classList.add('hidden');
}

// 页面加载时尝试获取当前位置天气
window.addEventListener('load', () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
                const { latitude, longitude } = position.coords;
                getWeatherByCoordinates(latitude, longitude);
            },
            error => {
                // 如果用户拒绝定位，不显示错误，让用户手动输入
                console.log('用户拒绝了定位请求');
            }
        );
    }
});